package ch.sfug.log.output {
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	
	import ch.sfug.log.output.ILoggerOutput;	

	/**
	 * @author loop
	 */
	public class LogPanel extends Sprite implements ILoggerOutput {

		private var txtfield:TextField;
		private var auto:Boolean;

		public function LogPanel( d:Stage, autoshow:Boolean = true ) {
			d.addChild(this);
			create();
			this.auto = autoshow;
			adjustSize(new Event(Event.RESIZE));
			d.addEventListener(Event.RESIZE, adjustSize);
		}

		
		/**
		 * creates the panel on the sprite
		 */
		private function create(  ):void {

			var bar_bg:Sprite = new Sprite();
			bar_bg.graphics.beginFill(0xAAAAAA, 0.5);
			bar_bg.graphics.drawRect(0, 0, 100, 18);
			bar_bg.name = "bar_bg";
			bar_bg.addEventListener(MouseEvent.CLICK, toggle);

			var label:TextField = new TextField();
			label.text = "log";
			label.height = 18;
			label.width = 100;
			label.mouseEnabled = false;

			txtfield = new TextField();
			txtfield.y = 18;
			txtfield.type = TextFieldType.INPUT;
			txtfield.background = true;
			txtfield.backgroundColor = 0xFFFFFF;
			txtfield.height = 150;
			txtfield.multiline = true;
			txtfield.wordWrap = true;


			var format:TextFormat = new TextFormat();
			format.font = "_sans";
			format.color = 0x000000;
			format.size = 10;
			txtfield.defaultTextFormat = format;


			addChild(bar_bg);
			addChild(label);
            //addChild( txtfield );
		}

		
		/**
		 * adjusts the size of the panel depending on the stage
		 */
		private function adjustSize( e:Event ):void {
			txtfield.width = stage.stageWidth;
			getChildByName("bar_bg").width = stage.stageWidth;
			this.y = stage.stageHeight - this.height;
		}

		
		/**
		 * toggles the output panel
		 */
		private function toggle( e:Event = null ):void {
			if( contains(txtfield) ) {
				removeChild(txtfield);
			} else {
				addChild(txtfield);
			}
			adjustSize(new Event(Event.RESIZE));
		}

		
		public function append( txt:String ):void {
			txtfield.text = txt + "\n" + txtfield.text;
			if( auto && !contains(txtfield) ) toggle();
		}

		
		public function clear(  ):void {
			txtfield.text = "";
		}
	}
}
